package sgf;

import java.awt.Point;
import java.util.ArrayList;

/**
 * Utilities for working with SGF.
 * @author TKington
 *
 */
public class SGFUtils {
	/**
	 * Converts a character to the corresponding coordinate value.
	 * @param c the character
	 * @return the int coordinate
	 */
    private static int charToNum(char c) {
        if(c >= 'a' && c <= 'z')
            return c - 'a';
        return c - 'A';
    }
    
    /**
     * Converts a string like ac to a Point.
     * @param s the string
     * @return the Point
     * @throws SGFParseException
     */
    public static Point stringToPoint(String s) throws SGFParseException {
        if(s.length() != 2)
            throw new SGFParseException("Invalid coordinates" + " \""
                                        + s + "\" " + "in sgf file");
        return new Point(charToNum(s.charAt(0)), charToNum(s.charAt(1)));
    }
    
    /**
     * Converts a string like ac or aa:cc to a list of Points.
     * @param s the string
     * @return the list of Points
     * @throws SGFParseException
     */
    public static ArrayList<Point> stringToPoints(String s) throws SGFParseException {
    	ArrayList<Point> list = new ArrayList<Point>();
    	if(s.length() == 2) {
    		list.add(stringToPoint(s));
    		return list;
    	}
    	
    	if(s.length() != 5 || s.charAt(2) != ':')
            throw new SGFParseException("Invalid coordinates" + " \""
                    + s + "\" " + "in sgf file");

    	Point p1 = stringToPoint(s.substring(0, 2));
    	Point p2 = stringToPoint(s.substring(3, 5));

    	int minx = Math.min(p1.x, p2.x);
    	int miny = Math.min(p1.y, p2.y);
    	int maxx = Math.max(p1.x, p2.x);
    	int maxy = Math.max(p1.y, p2.y);
    	
    	for(int x = minx; x <= maxx; x++) {
    		for(int y = miny; y <= maxy; y++) {
    			list.add(new Point(x,y));
    		}
    	}
    	
    	return list;
    }
    
    /**
     * Checks to see if a Point is legal on a Board of a given size.
     * @param p the Point
     * @param size the Board size
     * @throws SGFParseException if the Point is illegal
     */
    public static void checkPoint(Point p, int size) throws SGFParseException {
    	//	TODO: Eliminate SGFParseExceptions by passing Point rather than lists of String
        if(p.x < 0 || p.x >= size || p.y < 0 || p.y >= size)
            throw new SGFParseException("Invalid coordinates:"
                                        + " " + p.x + "," + p.y); //$NON-NLS-1$ //$NON-NLS-2$
    }
}
